<template>
  <div ref="chartRef" :style="{ width: width, height: height }" class="chart-container"></div>
</template>

<script>
import * as echarts from 'echarts'
import { debounce } from '@/utils/index'

export default {
  name: 'EchartWrapper',
  props: {
    // 图表配置项
    options: {
      type: Object,
      required: true
    },
    // 图表宽度
    width: {
      type: String,
      default: '100%'
    },
    // 图表高度
    height: {
      type: String,
      default: '300px'
    },
    // 主题
    theme: {
      type: String,
      default: ''
    },
    // 是否自动调整大小
    autoResize: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      chart: null,
      resizeObserver: null
    }
  },
  watch: {
    options: {
      handler(newOptions) {
        this.setOptions(newOptions)
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
    if (this.autoResize) {
      this.__resizeHandler = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)
      window.addEventListener('resize', this.__resizeHandler)
      
      // 使用ResizeObserver观察容器大小变化
      if (typeof ResizeObserver !== 'undefined') {
        this.resizeObserver = new ResizeObserver(this.__resizeHandler)
        this.resizeObserver.observe(this.$refs.chartRef)
      }
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    if (this.autoResize) {
      window.removeEventListener('resize', this.__resizeHandler)
      if (this.resizeObserver) {
        this.resizeObserver.disconnect()
      }
    }
    
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      if (!this.$refs.chartRef) return
      this.chart = echarts.init(this.$refs.chartRef, this.theme)
      this.setOptions(this.options)
      
      // 添加点击事件监听
      this.chart.on('click', (params) => {
        this.$emit('chart-click', params)
      })
    },
    setOptions(options) {
      if (this.chart) {
        this.chart.setOption(options, true)
      }
    },
    // 对外暴露获取实例的方法
    getInstance() {
      return this.chart
    },
    // 主动触发图表重绘
    resize() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    // 刷新图表
    refreshChart() {
      if (this.chart) {
        this.chart.setOption(this.options, true)
      }
    }
  }
}
</script>

<style scoped>
.chart-container {
  position: relative;
}
</style> 